//    var str = "abc def ggabcgg";
//    console.log(str.match(/\babc\b/g))//输出abc \b匹配单词边界
//    var a = "abc";
//    var reg = new RegExp("\\b"+a+"\\b","g");
//    var reg2 = new RegExp(/\babc\b/,"g");
//    console.log(str.match(reg))//输出abc
//    console.log(str.match(reg2));//输出abc
function log(str) {
    console.log(str);
}

function trim(str) {
    return str.replace(/^\s+|\s+$/g, "");
}

function byClass(parent, sel) {
    //IE8及以下不支持getElemntsByClassName方法，所以处理一下兼容性
    //      if(parent.getElementsByClassName){
    //        //如果支持byClassName方法   直接返回选择到的元素
    //        return parent.getElementsByClassName(sel);
    //      }
    //获取元素下所有元素的方法 （包括深层次的元素）
    var eles = parent.getElementsByTagName("*");
    var reg = new RegExp("\\b" + sel + "\\b");
    var arr = []; //用于存放匹配到的元素
    for (var i = 0; i < eles.length; i++) {
        //得到每一个元素 得到每一个元素的class名称
        var ele = eles[i],
            cName = ele.className;
        // "wrap" "wrap wrap2"
        if (reg.test(cName)) {
            arr.push(ele);
        }
    }
    return arr;
}

function getEl(sel) {
    sel = trim(sel);
    var parents = [];
    var childrens = [document];
    sel = sel.replace(/\s+/g, " ");
    sel = sel.split(" ");
    // "#main span" "div span"
    for (var m = 0; m < sel.length; m++) {
        parents = childrens;
        childrens = [];
        if (sel[m].charAt(0) == "#") {
            log("ID选择器");
            var _sel = sel[m].substring(1);
            for (var i = 0; i < parents.length; i++) {
                var ele = parents[i].getElementById(_sel);
                childrens.push(ele);
            }
        } else if (sel[m].charAt(0) == ".") {
            log("class选择器");
            var _sel = sel[m].substring(1);
            for (var i = 0; i < parents.length; i++) {
                var eles = byClass(parents[i], _sel);
                for (var k = 0; k < eles.length; k++) {
                    childrens.push(eles[k]);
                }
                //            childrens = eles;
            }
        } else {
            log("标签选择器");
            for (var i = 0; i < parents.length; i++) {
                var eles = parents[i].getElementsByTagName(sel[m]);
                for (var k = 0; k < eles.length; k++) {
                    childrens.push(eles[k]);
                }
            }
        }

    }
    return childrens;
}

log(getEl("#main .inner"));
